import { computed, reactive, ref } from 'vue'
import { useMessage } from 'wot-design-uni'
import { useUserStore } from '@/stores/user'
import { UserAPI } from '@/api'

// 用户信息接口
interface UserFormData {
  realname: string
  sex: string
  birthday: string
  phone: string
  email: string
}

// 性别选项 - 适配 wd-action-sheet 的 Action 接口
const sexOptions = [
  { name: '男', value: '1' },
  { name: '女', value: '2' },
  { name: '保密', value: '0' },
]

export function useUserCenter() {
  const userStore = useUserStore()
  const message = useMessage()
  // 用户信息表单
  const userForm = reactive<UserFormData>({
    realname: '',
    sex: '0',
    birthday: Date.now().toString(),
    phone: '',
    email: '',
  })

  // 状态管理
  const loading = ref(false)
  const showSexPicker = ref(false)
  const showBirthdayPicker = ref(false)
  const showPasswordDialog = ref(false)
  const showVipDialog = ref(false)

  // 编辑状态管理
  const isEditingNickname = ref(false)
  const isEditingPhone = ref(false)
  const isEditingEmail = ref(false)

  // 临时生日值 - 使用时间戳格式
  const tempBirthday = ref<number>(
    userForm.birthday ? new Date(userForm.birthday).getTime() : Date.now(),
  )

  // 密码表单
  const passwordForm = reactive({
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
  })

  // 会员兑换码
  const vipCode = ref('')

  // 计算属性：用户信息
  const userInfo = computed(() => userStore.userInfo)

  // 计算属性：日期选择器范围
  const dateRange = computed(() => {
    // 最小日期：1900年1月1日
    const minDate = new Date('1900-01-01').getTime()
    // 最大日期：当前时间
    const maxDate = Date.now()

    return {
      minDate,
      maxDate,
    }
  })

  // 统一的工具函数
  const utils = {
    // 显示Toast提示
    showToast(title: string, icon: 'success' | 'error' | 'none' = 'success') {
      uni.showToast({ title, icon })
    },

    // 显示确认弹窗
    showModal(options: {
      title: string
      content: string
      confirmText?: string
      confirmColor?: string
    }) {
      return new Promise<{ confirm: boolean }>((resolve) => {
        uni.showModal({
          ...options,
          success: resolve,
        })
      })
    },

    // 统一的异步操作包装器
    async withLoading<T>(
      operation: () => Promise<T>,
      successMessage?: string,
      errorMessage = '操作失败',
    ): Promise<T | null> {
      loading.value = true
      try {
        const result = await operation()
        console.log('withLoading - 操作结果:', result)

        // 如果result是字符串，直接显示
        if (typeof result === 'string') {
          console.log('withLoading - 显示字符串结果:', result)
          this.showToast(result)
        }
        // 如果result是对象且包含message字段，使用它作为提示信息
        else if (result && typeof result === 'object' && 'message' in result) {
          console.log('withLoading - 显示result中的message:', (result as any).message)
          this.showToast((result as any).message)
        }
        // 否则使用传入的默认成功消息
        else if (successMessage) {
          console.log('withLoading - 显示默认成功消息:', successMessage)
          this.showToast(successMessage)
        }
        else {
          console.log('withLoading - 没有显示任何消息')
        }

        return result
      }
      catch (error) {
        console.log('withLoading - 捕获错误:', error)
        // 如果错误对象包含message字段，使用它作为错误提示
        if (error && typeof error === 'object' && 'message' in error) {
          console.log('withLoading - 显示错误中的message:', (error as any).message)
          this.showToast((error as any).message, 'error')
        }
        // 否则使用传入的默认错误消息
        else {
          console.error(errorMessage, error)
          this.showToast(errorMessage, 'error')
        }
        return null
      }
      finally {
        loading.value = false
      }
    },

    // 页面跳转
    navigateTo(url: string) {
      uni.reLaunch({ url })
    },
  }

  // 格式化生日显示
  function formatBirthday(birthday: string | null | undefined): string {
    if (!birthday)
      return '未设置'

    try {
      const date = new Date(birthday)
      return Number.isNaN(date.getTime()) ? '未设置' : date.toISOString().split('T')[0]
    }
    catch {
      return '未设置'
    }
  }

  // 获取性别显示文本
  function getSexText(sex: string) {
    return sexOptions.find(item => item.value === sex)?.name || '保密'
  }

  // 保存用户信息
  const saveUserInfo = async (field?: string, value?: string, oldValue?: string) => {
    console.log('保存用户信息', field, value, oldValue)

    if (!userInfo.value)
      return

    const result = await utils.withLoading(
      async () => {
        // 如果传入了field和value，则使用新的接口格式
        if (field && value !== undefined) {
          const params: any = {
            field,
            value,
          }

          // 如果有oldValue，添加到参数中
          if (oldValue !== undefined) {
            params.oldValue = oldValue
          }

          console.log('调用API参数:', params)
          const result = await UserAPI.updateUserInfo(params)
          console.log('API返回结果:', result)

          // 检查API返回结果
          if (!result) {
            throw new Error('API返回空结果')
          }

          // 更新本地状态（只更新非特殊字段）
          if (userInfo.value) {
            switch (field) {
              case 'realname':
                userInfo.value.realname = value
                break
              case 'sex':
                userInfo.value.sex = value
                break
              case 'birthday':
                userInfo.value.birthday = value
                break
              case 'phone':
                userInfo.value.phone = value
                break
              case 'email':
                userInfo.value.email = value
                break
              // 特殊字段不更新本地状态
              case 'password':
              case 'vip':
              case 'gift':
              case 'cancel':
                break
            }
          }

          // 返回result中的提示信息
          return result
        }
        else {
          // 兼容旧的更新方式，逐个字段更新
          const fields = [
            { field: 'realname', value: userForm.realname },
            { field: 'sex', value: userForm.sex },
            { field: 'birthday', value: userForm.birthday },
            { field: 'phone', value: userForm.phone },
            { field: 'email', value: userForm.email },
          ]

          let lastResult = null
          let hasUpdates = false
          for (const { field: f, value: v } of fields) {
            if (v && v !== userInfo.value![f as keyof typeof userInfo.value]) {
              hasUpdates = true
              const params = {
                userId: userInfo.value!.id,
                field: f,
                value: v,
              }
              const result = await UserAPI.updateUserInfo(params)

              // 更新本地状态
              if (userInfo.value) {
                (userInfo.value as any)[f] = v
              }

              // 保存最后一个result
              lastResult = result
            }
          }

          // 如果没有更新任何字段，返回默认成功消息
          if (!hasUpdates) {
            return '保存成功'
          }

          // 返回最后一个result
          return lastResult
        }
      },
      undefined, // 不使用默认成功消息，而是使用result中的消息
      undefined, // 不使用默认错误消息，而是使用API返回的错误消息
    )

    console.log('saveUserInfo最终结果:', result)
    return result
  }

  // 初始化表单数据
  const initFormData = () => {
    console.log('初始化表单数据，userInfo.value:', userInfo.value)
    if (userInfo.value) {
      userForm.realname = userInfo.value.realname || ''
      userForm.sex = userInfo.value.sex?.toString() || '0'

      // 确保生日格式为 YYYY-MM-DD
      if (userInfo.value.birthday) {
        const birthdayDate = new Date(userInfo.value.birthday)
        if (!Number.isNaN(birthdayDate.getTime())) {
          const year = birthdayDate.getFullYear()
          const month = String(birthdayDate.getMonth() + 1).padStart(2, '0')
          const day = String(birthdayDate.getDate()).padStart(2, '0')
          userForm.birthday = `${year}-${month}-${day}`
        }
        else {
          userForm.birthday = ''
        }
      }
      else {
        userForm.birthday = ''
      }

      userForm.phone = userInfo.value.phone || ''
      userForm.email = userInfo.value.email || ''

      console.log('初始化后的userForm:', userForm)
      console.log('userForm.birthday:', userForm.birthday)
    }
  }

  // 头像上传
  const handleAvatarUpload = () => {
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const tempFilePath = res.tempFilePaths[0]

        await utils.withLoading(
          async () => {
            const result = await UserAPI.uploadAvatar(tempFilePath)
            console.log('头像上传结果:', result)

            if (result && userInfo.value) {
              // 根据实际返回格式获取头像地址
              let avatarUrl = ''

              if (typeof result === 'string') {
                // 如果返回的是字符串，直接使用
                avatarUrl = result
              }
              else if (result && typeof result === 'object') {
                // 如果返回的是对象，优先使用 message 字段，然后是 result 字段
                avatarUrl = (result as any).message || (result as any).result || (result as any).avatar || ''
              }

              if (avatarUrl) {
                // 更新用户信息中的头像
                userInfo.value.avatar = avatarUrl
                console.log('头像已更新:', avatarUrl)

                // 返回成功消息，使用API返回的message或默认消息
                const successMessage = '头像上传成功'
                return { message: successMessage }
              }
              else {
                throw new Error('未获取到头像地址')
              }
            }
            else {
              throw new Error('上传失败')
            }
          },
          undefined, // 使用API返回的提示信息
          '头像上传失败',
        )
      },
    })
  }

  // 监听生日选择器打开，同步当前值
  function handleBirthdayPickerOpen() {
    console.log('打开生日选择器，当前userForm.birthday:', userForm.birthday)
    if (userForm.birthday) {
      // 确保转换为时间戳格式
      const date = new Date(userForm.birthday)
      tempBirthday.value = date.getTime()
      console.log('转换后的时间戳:', tempBirthday.value)
    }
    else {
      tempBirthday.value = Date.now()
      console.log('使用当前时间戳:', tempBirthday.value)
    }
  }

  // 字段配置映射
  const fieldConfig = {
    nickname: {
      editingRef: isEditingNickname,
      formValue: () => userForm.realname,
      userValue: () => userInfo.value?.realname || '',
      apiField: 'realname',
    },
    phone: {
      editingRef: isEditingPhone,
      formValue: () => userForm.phone,
      userValue: () => userInfo.value?.phone || '',
      apiField: 'phone',
    },
    email: {
      editingRef: isEditingEmail,
      formValue: () => userForm.email,
      userValue: () => userInfo.value?.email || '',
      apiField: 'email',
    },
  } as const

  // 统一的编辑处理函数
  function handleEdit(field: keyof typeof fieldConfig) {
    fieldConfig[field].editingRef.value = true
  }

  // 统一的失焦/确认处理函数
  async function handleFieldAction(field: keyof typeof fieldConfig) {
    const config = fieldConfig[field]
    const isEditing = config.editingRef.value
    const formValue = config.formValue()
    const userValue = config.userValue()

    // 关闭编辑状态
    config.editingRef.value = false

    // 只有当值发生变化且不为空时才保存
    if (isEditing && formValue !== userValue && formValue.trim()) {
      await saveUserInfo(config.apiField, formValue.trim())
    }
  }

  // 处理生日确认
  async function handleBirthdayConfirm() {
    console.log('确认生日选择，tempBirthday.value:', tempBirthday.value)
    // tempBirthday.value 是时间戳格式，需要转换为 YYYY-MM-DD 格式
    const selectedDate = new Date(tempBirthday.value)

    // 使用本地时间，避免时区问题
    const year = selectedDate.getFullYear()
    const month = String(selectedDate.getMonth() + 1).padStart(2, '0')
    const day = String(selectedDate.getDate()).padStart(2, '0')
    const newBirthday = `${year}-${month}-${day}`

    console.log('转换后的日期格式:', newBirthday)
    console.log('当前userForm.birthday:', userForm.birthday)

    // 只有当值发生变化时才保存
    if (newBirthday !== userForm.birthday) {
      console.log('生日值发生变化，准备保存:', newBirthday)
      userForm.birthday = newBirthday
      await saveUserInfo('birthday', newBirthday)
    }
    else {
      console.log('生日值没有变化，不保存')
    }
    showBirthdayPicker.value = false
  }

  // 重写性别选择处理
  async function handleSexSelect(action: any) {
    console.log('性别选择action:', action)
    console.log('action.item:', action.item)
    console.log('action.index:', action.index)
    console.log('当前userForm.sex:', userForm.sex)

    // 尝试从不同位置获取选中的值
    let selectedValue = null

    // 如果action.item存在，使用item中的value
    if (action.item && action.item.value) {
      selectedValue = action.item.value
    }
    // 如果action.item存在但没有value，尝试使用name找到对应的value
    else if (action.item && action.item.name) {
      const option = sexOptions.find(item => item.name === action.item.name)
      selectedValue = option?.value
    }
    // 如果action.index存在，通过索引获取对应的选项
    else if (action.index !== undefined && action.index >= 0 && action.index < sexOptions.length) {
      selectedValue = sexOptions[action.index].value
    }

    console.log('最终选中的值:', selectedValue)

    // 只有当值发生变化时才保存
    if (selectedValue && selectedValue !== userForm.sex) {
      console.log('性别值发生变化，准备保存:', selectedValue)
      userForm.sex = selectedValue
      await saveUserInfo('sex', selectedValue)
    }
    else {
      console.log('性别值没有变化，不保存')
    }
    showSexPicker.value = false
  }

  // 修改密码
  const changePassword = async () => {
    if (!passwordForm.oldPassword || !passwordForm.newPassword || !passwordForm.confirmPassword) {
      utils.showToast('请填写完整信息', 'none')
      return
    }

    if (passwordForm.newPassword !== passwordForm.confirmPassword) {
      utils.showToast('两次密码不一致', 'none')
      return
    }

    await utils.withLoading(
      async () => {
        const result = await UserAPI.changePassword({
          userId: userInfo.value?.id || '',
          field: 'password',
          value: passwordForm.newPassword,
        })

        // 清空表单
        passwordForm.oldPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''
        showPasswordDialog.value = false

        return result
      },
      undefined, // 使用API返回的提示信息
      undefined, // 使用API返回的错误信息
    )
  }

  // 会员兑换
  const exchangeVip = async () => {
    if (!vipCode.value) {
      utils.showToast('请输入兑换码', 'none')
      return
    }

    await utils.withLoading(
      async () => {
        // 这里应该调用实际的会员兑换API
        const result = await new Promise(resolve => setTimeout(() => resolve({ message: '兑换成功' }), 1000))

        vipCode.value = ''
        showVipDialog.value = false

        return result
      },
      undefined, // 使用API返回的提示信息
      undefined, // 使用API返回的错误信息
    )
  }

  // 注销账户
  const logoutAccount = async () => {
    const res = await utils.showModal({
      title: '确认注销',
      content: '注销后账户将无法恢复，确定要注销吗？',
      confirmText: '确认注销',
      confirmColor: '#ff4757',
    })

    if (res.confirm) {
      await utils.withLoading(
        async () => {
          // 这里应该调用实际的注销API
          const result = await new Promise(resolve => setTimeout(() => resolve({ message: '账户已注销' }), 1000))

          // 执行退出登录
          await userStore.logout()

          // 跳转到首页
          utils.navigateTo('/pages/home/index')

          return result
        },
        undefined, // 使用API返回的提示信息
        undefined, // 使用API返回的错误信息
      )
    }
  }

  // 退出登录
  const handleLogout = async () => {
    const res = await utils.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
    })

    if (res.confirm) {
      await utils.withLoading(
        async () => {
          await userStore.logout()
          // 跳转到登录页
          utils.navigateTo('/pages/login/index')

          return { message: '已退出登录' }
        },
        undefined, // 使用API返回的提示信息
        undefined, // 使用API返回的错误信息
      )
    }
  }

  // 账户管理相关函数
  const accountActions = {
    // 修改密码
    changePassword: async () => {
      try {
        const newPasswordResp = await message.prompt({
          title: '请输入新密码',
          inputPlaceholder: '请输入新密码',
          inputType: 'text',
          inputPattern: /^.{6,}$/,
          inputError: '密码至少6位',
        })

        const newPassword = String(newPasswordResp.value || '')

        const confirmPasswordResp = await message.prompt({
          title: '请再次输入新密码',
          inputPlaceholder: '请再次输入新密码',
          inputType: 'text',
          inputPattern: new RegExp(`^${newPassword}$`),
          inputError: '两次密码不一致',
        })

        const confirmPassword = String(confirmPasswordResp.value || '')

        if (newPassword === confirmPassword) {
          const result = await saveUserInfo('password', newPassword)

          // 密码修改成功后执行退出登录操作
          if (result) {
            // 先显示成功提示
            utils.showToast('密码修改成功，请重新登录', 'success')

            // 延迟一下再退出登录，让用户看到提示
            setTimeout(() => {
              userStore.logout().then(() => {
                // 关闭所有页面并跳转到首页
                uni.reLaunch({
                  url: '/pages/index/index',
                })
              })
            }, 1500)
          }
        }
      }
      catch (error) {
        console.log('用户取消或输入错误:', error)
      }
    },

    // 升级会员
    upgradeMember: async () => {
      try {
        const resp = await message.prompt({
          title: '请输入会员兑换码',
          msg: '',
          inputPlaceholder: '请输入兑换码',
          inputPattern: /^[A-Z0-9]{6,}$/,
          inputError: '请输入有效的兑换码',
        })

        const vipCode = String(resp.value || '')
        await saveUserInfo('vip', vipCode)
      }
      catch (error) {
        console.log('用户取消或输入错误:', error)
      }
    },

    // 兑换会员
    redeemMember: async () => {
      try {
        const resp = await message.prompt({
          title: '请输入会员兑换码',
          inputPlaceholder: '请输入兑换码',
          inputPattern: /^[A-Z0-9]{6,}$/,
          inputError: '请输入有效的兑换码',
        })

        const giftCode = String(resp.value || '')
        await saveUserInfo('gift', giftCode)
      }
      catch (error) {
        console.log('用户取消或输入错误:', error)
      }
    },

    // 注销账户
    deleteAccount: async () => {
      try {
        await message.confirm({
          title: '确认注销',
          msg: '注销后账户将无法恢复，确定要注销吗？',
          confirmButtonText: '确认注销',
          cancelButtonText: '取消',
        })

        await saveUserInfo('cancel', '1')
      }
      catch (error) {
        console.log('用户取消:', error)
      }
    },
  }

  const handleChangePassword = () => accountActions.changePassword()
  const handleUpgradeMember = () => accountActions.upgradeMember()
  const handleRedeemMember = () => accountActions.redeemMember()
  const handleDeleteAccount = () => accountActions.deleteAccount()

  // 初始化
  initFormData()

  return {
    // 数据
    userForm,
    userInfo,
    sexOptions,
    passwordForm,
    vipCode,
    loading,
    tempBirthday,
    dateRange,

    // 编辑状态
    isEditingNickname,
    isEditingPhone,
    isEditingEmail,

    // 状态
    showSexPicker,
    showBirthdayPicker,
    showPasswordDialog,
    showVipDialog,

    // 方法
    formatBirthday,
    getSexText,
    handleAvatarUpload,
    handleBirthdayPickerOpen,
    handleEdit,
    handleFieldAction,
    handleBirthdayConfirm,
    handleSexSelect,
    saveUserInfo,
    changePassword,
    exchangeVip,
    logoutAccount,
    handleLogout,
    handleChangePassword,
    handleUpgradeMember,
    handleRedeemMember,
    handleDeleteAccount,
  }
}
